package com.aaa.marketresearch.dataresource.dao;

import com.aaa.marketresearch.dataresource.domain.FamilyMember;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;

/**
 * @author Nail
 */

@Repository
public class FamilyMemberDAOImpl implements FamilyMemberDAO {

    @PersistenceContext
    private EntityManager em;

    @Override
    public List<FamilyMember> getAll() {
        List<FamilyMember> result = em.createQuery("FROM FamilyMember fm").getResultList();
        return result;
    }

    @Override
    public List<FamilyMember> getAllForFamily(Integer familyId) {
        final String query = "FROM FamilyMember fm WHERE fm.familyId=:familyId";

        List<FamilyMember> result = em.createQuery(query).setParameter("familyId", familyId).getResultList();
        return result;
    }

    @Override
    public FamilyMember getById(Integer id) {
        final String query = "FROM FamilyMember fm WHERE fm.id=:id";

        Object obj = em.createQuery(query).setParameter("id", id).getSingleResult();
        if (obj != null) {
            return (FamilyMember) obj;
        } else {
            return null;
        }
    }

    @Override
    public List<String> getProfessions(String part) {
        final String query;
        final List<String> result;
        if (part != null && part.length() > 0) {
            query = "SELECT DISTINCT fm.profession FROM FamilyMember fm WHERE lower(fm.profession) LIKE :part";
            result = em.createQuery(query).setParameter("part", part).getResultList();
        } else {
            query = "SELECT DISTINCT fm.profession FROM FamilyMember fm";
            result = em.createQuery(query).getResultList();
        }

        return result;
    }

    @Override
    public void save(FamilyMember familyMember) {
        this.em.merge(familyMember);
    }

    @Override
    public boolean delete(Integer id) {
        final String query = "DELETE FamilyMember fm WHERE fm.id = :id";
        int count = em.createQuery(query).setParameter("id", id).executeUpdate();
        return (count > 0);
    }
}